package com.lvyq.javaprint.ws;

import cn.hutool.json.JSONUtil;
import com.lvyq.javaprint.common.CommonResult;
import com.lvyq.javaprint.util.CommonUtils;
import com.lvyq.javaprint.util.PrintUtils;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lvyq
 * @version 1.0
 * @description: TODO
 * @date 2021/8/17 16:30
 */
@ServerEndpoint(value = "/print")
@Component
public class WebSocketServer {


    @PostConstruct
    public void init() {
        System.out.println("websocket 加载");
    }

    private static final AtomicInteger OnlineCount = new AtomicInteger(0);
    private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        SessionSet.add(session);
       // int cnt = OnlineCount.incrementAndGet();
        //String printService = PrintUtils.defaultPrintService();
        SendMessage(session, JSONUtil.toJsonStr(CommonResult.success(session.getId())));
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        SessionSet.remove(session);
        int cnt = OnlineCount.decrementAndGet();
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message) {
       /* PrintData vo = JSONUtil.toBean(message,PrintData.class);
        PDFPrintServer.printOne(vo);*/
    }

    /**
     * 出现错误
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * 发送消息，实践表明，每次浏览器刷新，session会发生变化。
     *
     * @param session
     * @param message
     */
    public static void SendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 指定Session发送消息
     *
     * @param sessionId
     * @param message
     * @throws IOException
     */
    public static void SendMessageById(String message, String sessionId){
        Session session = null;
        for (Session s : SessionSet) {
            if (s.getId().equals(sessionId)) {
                session = s;
                break;
            }
        }
        if (session != null) {
            SendMessage(session, message);
        } else {
        }
    }

    public static void SendMessageAll(String message){
        for (Session s : SessionSet) {
            SendMessage(s, message);
        }
    }
}
